home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / heapq.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-11-11  |  12.4 KB  |  287 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Heap queue algorithm (a.k.a. priority queue).
  5.  
  6. Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
  7. all k, counting elements from 0.  For the sake of comparison,
  8. non-existing elements are considered to be infinite.  The interesting
  9. property of a heap is that a[0] is always its smallest element.
  10.  
  11. Usage:
  12.  
  13. heap = []            # creates an empty heap
  14. heappush(heap, item) # pushes a new item on the heap
  15. item = heappop(heap) # pops the smallest item from the heap
  16. item = heap[0]       # smallest item on the heap without popping it
  17. heapify(x)           # transforms list into a heap, in-place, in linear time
  18. item = heapreplace(heap, item) # pops and returns smallest item, and adds
  19.                                # new item; the heap size is unchanged
  20.  
  21. Our API differs from textbook heap algorithms as follows:
  22.  
  23. - We use 0-based indexing.  This makes the relationship between the
  24.   index for a node and the indexes for its children slightly less
  25.   obvious, but is more suitable since Python uses 0-based indexing.
  26.  
  27. - Our heappop() method returns the smallest item, not the largest.
  28.  
  29. These two make it possible to view the heap as a regular Python list
  30. without surprises: heap[0] is the smallest item, and heap.sort()
  31. maintains the heap invariant!
  32. '''
  33. __about__ = 'Heap queues\n\n[explanation by Fran\xe7ois Pinard]\n\nHeaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\nall k, counting elements from 0.  For the sake of comparison,\nnon-existing elements are considered to be infinite.  The interesting\nproperty of a heap is that a[0] is always its smallest element.\n\nThe strange invariant above is meant to be an efficient memory\nrepresentation for a tournament.  The numbers below are `k\', not a[k]:\n\n                                   0\n\n                  1                                 2\n\n          3               4                5               6\n\n      7       8       9       10      11      12      13      14\n\n    15 16   17 18   19 20   21 22   23 24   25 26   27 28   29 30\n\n\nIn the tree above, each cell `k\' is topping `2*k+1\' and `2*k+2\'.  In\nan usual binary tournament we see in sports, each cell is the winner\nover the two cells it tops, and we can trace the winner down the tree\nto see all opponents s/he had.  However, in many computer applications\nof such tournaments, we do not need to trace the history of a winner.\nTo be more memory efficient, when a winner is promoted, we try to\nreplace it by something else at a lower level, and the rule becomes\nthat a cell and the two cells it tops contain three different items,\nbut the top cell "wins" over the two topped cells.\n\nIf this heap invariant is protected at all time, index 0 is clearly\nthe overall winner.  The simplest algorithmic way to remove it and\nfind the "next" winner is to move some loser (let\'s say cell 30 in the\ndiagram above) into the 0 position, and then percolate this new 0 down\nthe tree, exchanging values, until the invariant is re-established.\nThis is clearly logarithmic on the total number of items in the tree.\nBy iterating over all items, you get an O(n ln n) sort.\n\nA nice feature of this sort is that you can efficiently insert new\nitems while the sort is going on, provided that the inserted items are\nnot "better" than the last 0\'th element you extracted.  This is\nespecially useful in simulation contexts, where the tree holds all\nincoming events, and the "win" condition means the smallest scheduled\ntime.  When an event schedule other events for execution, they are\nscheduled into the future, so they can easily go into the heap.  So, a\nheap is a good structure for implementing schedulers (this is what I\nused for my MIDI sequencer :-).\n\nVarious structures for implementing schedulers have been extensively\nstudied, and heaps are good for this, as they are reasonably speedy,\nthe speed is almost constant, and the worst case is not much different\nthan the average case.  However, there are other representations which\nare more efficient overall, yet the worst cases might be terrible.\n\nHeaps are also very useful in big disk sorts.  You most probably all\nknow that a big sort implies producing "runs" (which are pre-sorted\nsequences, which size is usually related to the amount of CPU memory),\nfollowed by a merging passes for these runs, which merging is often\nvery cleverly organised[1].  It is very important that the initial\nsort produces the longest runs possible.  Tournaments are a good way\nto that.  If, using all the memory available to hold a tournament, you\nreplace and percolate items that happen to fit the current run, you\'ll\nproduce runs which are twice the size of the memory for random input,\nand much better for input fuzzily ordered.\n\nMoreover, if you output the 0\'th item on disk and get an input which\nmay not fit in the current tournament (because the value "wins" over\nthe last output value), it cannot fit in the heap, so the size of the\nheap decreases.  The freed memory could be cleverly reused immediately\nfor progressively building a second heap, which grows at exactly the\nsame rate the first heap is melting.  When the first heap completely\nvanishes, you switch heaps and start a new run.  Clever and quite\neffective!\n\nIn a word, heaps are useful memory structures to know.  I use them in\na few applications, and I think it is good to keep a `heap\' module\naround. :-)\n\n--------------------\n[1] The disk balancing algorithms which are current, nowadays, are\nmore annoying than clever, and this is a consequence of the seeking\ncapabilities of the disks.  On devices which cannot seek, like big\ntape drives, the story was quite different, and one had to be very\nclever to ensure (far in advance) that each tape movement will be the\nmost effective possible (that is, will best participate at\n"progressing" the merge).  Some tapes were even able to read\nbackwards, and this was also used to avoid the rewinding time.\nBelieve me, real good tape sorts were quite spectacular to watch!\nFrom all times, sorting has always been a Great Art! :-)\n'
  34. __all__ = [
  35.     'heappush',
  36.     'heappop',
  37.     'heapify',
  38.     'heapreplace',
  39.     'merge',
  40.     'nlargest',
  41.     'nsmallest',
  42.     'heappushpop']
  43. from itertools import islice, repeat, count, imap, izip, tee
  44. from operator import itemgetter, neg
  45. import bisect
  46.  
  47. def heappush(heap, item):
  48.     '''Push item onto heap, maintaining the heap invariant.'''
  49.     heap.append(item)
  50.     _siftdown(heap, 0, len(heap) - 1)
  51.  
  52.  
  53. def heappop(heap):
  54.     '''Pop the smallest item off the heap, maintaining the heap invariant.'''
  55.     lastelt = heap.pop()
  56.     if heap:
  57.         returnitem = heap[0]
  58.         heap[0] = lastelt
  59.         _siftup(heap, 0)
  60.     else:
  61.         returnitem = lastelt
  62.     return returnitem
  63.  
  64.  
  65. def heapreplace(heap, item):
  66.     '''Pop and return the current smallest value, and add the new item.
  67.  
  68.     This is more efficient than heappop() followed by heappush(), and can be
  69.     more appropriate when using a fixed-size heap.  Note that the value
  70.     returned may be larger than item!  That constrains reasonable uses of
  71.     this routine unless written as part of a conditional replacement:
  72.  
  73.         if item > heap[0]:
  74.             item = heapreplace(heap, item)
  75.     '''
  76.     returnitem = heap[0]
  77.     heap[0] = item
  78.     _siftup(heap, 0)
  79.     return returnitem
  80.  
  81.  
  82. def heappushpop(heap, item):
  83.     '''Fast version of a heappush followed by a heappop.'''
  84.     if heap and heap[0] < item:
  85.         item = heap[0]
  86.         heap[0] = item
  87.         _siftup(heap, 0)
  88.     
  89.     return item
  90.  
  91.  
  92. def heapify(x):
  93.     '''Transform list into a heap, in-place, in O(len(heap)) time.'''
  94.     n = len(x)
  95.     for i in reversed(xrange(n // 2)):
  96.         _siftup(x, i)
  97.     
  98.  
  99.  
  100. def nlargest(n, iterable):
  101.     '''Find the n largest elements in a dataset.
  102.  
  103.     Equivalent to:  sorted(iterable, reverse=True)[:n]
  104.     '''
  105.     it = iter(iterable)
  106.     result = list(islice(it, n))
  107.     if not result:
  108.         return result
  109.     heapify(result)
  110.     _heappushpop = heappushpop
  111.     for elem in it:
  112.         _heappushpop(result, elem)
  113.     
  114.     result.sort(reverse = True)
  115.     return result
  116.  
  117.  
  118. def nsmallest(n, iterable):
  119.     '''Find the n smallest elements in a dataset.
  120.  
  121.     Equivalent to:  sorted(iterable)[:n]
  122.     '''
  123.     if hasattr(iterable, '__len__') and n * 10 <= len(iterable):
  124.         it = iter(iterable)
  125.         result = sorted(islice(it, 0, n))
  126.         if not result:
  127.             return result
  128.         insort = bisect.insort
  129.         pop = result.pop
  130.         los = result[-1]
  131.         for elem in it:
  132.             if los <= elem:
  133.                 continue
  134.             
  135.             insort(result, elem)
  136.             pop()
  137.             los = result[-1]
  138.         
  139.         return result
  140.     h = list(iterable)
  141.     heapify(h)
  142.     return map(heappop, repeat(h, min(n, len(h))))
  143.  
  144.  
  145. def _siftdown(heap, startpos, pos):
  146.     newitem = heap[pos]
  147.     while pos > startpos:
  148.         parentpos = pos - 1 >> 1
  149.         parent = heap[parentpos]
  150.         if newitem < parent:
  151.             heap[pos] = parent
  152.             pos = parentpos
  153.             continue
  154.         
  155.         break
  156.     heap[pos] = newitem
  157.  
  158.  
  159. def _siftup(heap, pos):
  160.     endpos = len(heap)
  161.     startpos = pos
  162.     newitem = heap[pos]
  163.     childpos = 2 * pos + 1
  164.     while childpos < endpos:
  165.         rightpos = childpos + 1
  166.         if rightpos < endpos and not (heap[childpos] < heap[rightpos]):
  167.             childpos = rightpos
  168.         
  169.         heap[pos] = heap[childpos]
  170.         pos = childpos
  171.         childpos = 2 * pos + 1
  172.     heap[pos] = newitem
  173.     _siftdown(heap, startpos, pos)
  174.  
  175.  
  176. try:
  177.     from _heapq import heappush, heappop, heapify, heapreplace, nlargest, nsmallest, heappushpop
  178. except ImportError:
  179.     pass
  180.  
  181.  
  182. def merge(*iterables):
  183.     '''Merge multiple sorted inputs into a single sorted output.
  184.  
  185.     Similar to sorted(itertools.chain(*iterables)) but returns a generator,
  186.     does not pull the data into memory all at once, and assumes that each of
  187.     the input streams is already sorted (smallest to largest).
  188.  
  189.     >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25]))
  190.     [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25]
  191.  
  192.     '''
  193.     _heappop = heappop
  194.     _heapreplace = heapreplace
  195.     _StopIteration = StopIteration
  196.     h = []
  197.     h_append = h.append
  198.     for itnum, it in enumerate(map(iter, iterables)):
  199.         
  200.         try:
  201.             next = it.next
  202.             h_append([
  203.                 next(),
  204.                 itnum,
  205.                 next])
  206.         continue
  207.         except _StopIteration:
  208.             continue
  209.         
  210.  
  211.     
  212.     heapify(h)
  213.     while None:
  214.         
  215.         try:
  216.             while None:
  217.                 yield v
  218.                 s[0] = next()
  219.                 _heapreplace(h, s)
  220.             continue
  221.             except _StopIteration:
  222.                 None<EXCEPTION MATCH>_StopIteration
  223.                 None<EXCEPTION MATCH>_StopIteration
  224.                 _heappop(h)
  225.                 continue
  226.                 except IndexError:
  227.                     return None
  228.                 
  229.                 return None
  230.  
  231.  
  232. _nsmallest = nsmallest
  233.  
  234. def nsmallest(n, iterable, key = None):
  235.     '''Find the n smallest elements in a dataset.
  236.  
  237.     Equivalent to:  sorted(iterable, key=key)[:n]
  238.     '''
  239.     if key is None:
  240.         it = izip(iterable, count())
  241.         result = _nsmallest(n, it)
  242.         return map(itemgetter(0), result)
  243.     (in1, in2) = tee(iterable)
  244.     it = izip(imap(key, in1), count(), in2)
  245.     result = _nsmallest(n, it)
  246.     return map(itemgetter(2), result)
  247.  
  248. _nlargest = nlargest
  249.  
  250. def nlargest(n, iterable, key = None):
  251.     '''Find the n largest elements in a dataset.
  252.  
  253.     Equivalent to:  sorted(iterable, key=key, reverse=True)[:n]
  254.     '''
  255.     if key is None:
  256.         it = izip(iterable, imap(neg, count()))
  257.         result = _nlargest(n, it)
  258.         return map(itemgetter(0), result)
  259.     (in1, in2) = tee(iterable)
  260.     it = izip(imap(key, in1), imap(neg, count()), in2)
  261.     result = _nlargest(n, it)
  262.     return map(itemgetter(2), result)
  263.  
  264. if __name__ == '__main__':
  265.     heap = []
  266.     data = [
  267.         1,
  268.         3,
  269.         5,
  270.         7,
  271.         9,
  272.         2,
  273.         4,
  274.         6,
  275.         8,
  276.         0]
  277.     for item in data:
  278.         heappush(heap, item)
  279.     
  280.     sort = []
  281.     while heap:
  282.         sort.append(heappop(heap))
  283.     print sort
  284.     import doctest
  285.     doctest.testmod()
  286.  
  287.